/*
 * Auther:Guan Junming <junming.guan at kisters.cn> Created:12-Oct-2011 14:07:45
 * Company:Kisters AG
 */
package cn.eclass.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.eclass.bean.api.IUserBean;
import cn.eclass.entity.CategoryEntity;
import cn.eclass.entity.UserEntity;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.ConstantsConf;
import cn.eclass.utils.Helper;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author Guan Junming <junming.guan at kisters.cn>
 */
public abstract class ActionFace {

    public BeanFactory beanFactory = BeanFactory.factory;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected Logger logger = Helper.getLogger();
    protected HttpSession session;
    protected PrintWriter out;
    protected String root;// = http://localhost:port/context/
    protected String adminRoot;// = http://localhost:port/context/admin/
    protected String module;// = index
    protected String action;// = index
    protected String view;// = index.jsp
    protected String adminView;// = /admin/iframe/index.jsp
    protected String url;// = do?module=index&action=index
    protected String adminUrl;// = admin/do?module=index&action=index
    protected String tableView;//=/admin/iframe/gridtable.jsp
    protected String adminModule;// = http://localhost:port/context/admin/do?module=moduleName
    protected String rootPath;//D://home/path
    protected String uploadRoot;//D://home/path/upload
    protected Gson gsonNull;
    protected Properties config;
    protected List<CategoryEntity> categoryTree;//spceial business requirement
    protected UserEntity user = null;
    protected String logInView = null;//This is the view for log in page, only happen in user pages. 

    public abstract void doIndex();

    public void execute(ActionFace instance) {
        String action = "doIndex";
        this.execute(instance, action);
    }

    public void execute(ActionFace instance, String action) {
        this.module = instance.getClass().getSimpleName().toLowerCase();
        this.action = action;
        this.view = "/" + this.module + ".jsp";
        this.adminView = "/admin/iframe/" + this.module + ".jsp";
        this.tableView = "/admin/iframe/tablegrid.jsp";
        this.url = "do?module" + module + "&action=" + action;
        this.adminUrl = "/admin" + this.url;
        this.adminModule = this.root + "/admin/do?module=" + module;
        this.config = Helper.getConfig();
        this.uploadRoot = config.getProperty("upload");
        this.categoryTree = BeanFactory.factory.getCatBean().getRoot().getChildren();

        logInView = "/login.jsp";

        String userName = (String) session.getAttribute(ConstantsConf.SESSION_USERNAME);
        if (userName != null) {
            IUserBean userBean = beanFactory.getUserBean();
            user = userBean.getByName(userName);
            if (user != null) {
                session.setAttribute(ConstantsConf.REQUEST_USERENTITY, user);
            }
        }

        this.request.setAttribute("module", module);
        this.request.setAttribute("adminModule", adminModule);
        this.request.setAttribute("adminRoot", adminRoot);
        this.request.setAttribute("root", root);
        this.request.setAttribute("categoryTree", categoryTree);

        try {
            Method method = instance.getClass().getMethod("do" + action);
            method.invoke(instance);
        } catch (IllegalAccessException ex) {
            logger.error(ex);
        } catch (IllegalArgumentException ex) {
            logger.error(ex);
        } catch (InvocationTargetException ex) {
            logger.error(ex);
        } catch (NoSuchMethodException ex) {
            logger.error(ex);
        } catch (SecurityException ex) {
            logger.error(ex);
        }

    }

    public void setRequestAndResponse(HttpServletRequest request, HttpServletResponse response) {
        try {
            this.request = request;
            this.response = response;
            this.session = request.getSession();
            this.response.setCharacterEncoding("UTF-8");
            this.out = response.getWriter();
            this.root = request.getContextPath();
            this.adminRoot = this.root + "/admin/";
            this.rootPath = request.getSession().getServletContext().getRealPath("/");
            this.gsonNull = new GsonBuilder().serializeNulls().create();
        } catch (IOException ex) {
            logger.error(ex);
        }
    }

    public String toJsonWithNull(Object object) {
        return gsonNull.toJson(object);
    }

    protected void echoAjaxSuccess(String message) {
        out.print(getAjaxResult("success", message));
    }

    protected void echoAjaxError(String message) {
        out.print(getAjaxResult("error", message));
    }

    protected String getAjaxResult(String status, String message) {
        Map<String, String> result = new HashMap<String, String>();
        result.put("status", status);
        result.put("message", message);
        return new Gson().toJson(result);
    }
}
